#!/bin/bash

# Script to remove git repositories created by addgit.sh
# Usage: ./rmgit.sh <repository_name1> [repository_name2] [...]

# Configuration (should match addgit.sh)
GIT_SERVER_BASE="/home/linden/code/gitee/git-server"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Input validation
if [ $# -eq 0 ]; then
    echo -e "${RED}Error: At least one repository name is required${NC}"
    echo "Usage: $0 <repository_name1> [repository_name2] [...]"
    exit 1
fi

# Function to validate repository name
validate_repo_name() {
    local repo_name="$1"
    if [[ ! "$repo_name" =~ ^[a-zA-Z0-9_-]+$ ]]; then
        echo -e "${RED}Error: Repository name '$repo_name' can only contain letters, numbers, underscores, and hyphens${NC}"
        return 1
    fi
    return 0
}

# Function to remove a single repository
remove_repository() {
    local repository_name="$1"
    local repo_path="$GIT_SERVER_BASE/$repository_name"
    
    echo -e "${YELLOW}Removing git repository: $repository_name${NC}"
    
    # Check if bare repository exists
    if [ -d "$repo_path" ]; then
        echo -e "${YELLOW}Found bare repository at: $repo_path${NC}"
        read -p "Are you sure you want to delete it? (y/N): " confirm
        
        if [[ $confirm =~ ^[Yy]$ ]]; then
            rm -rf "$repo_path"
            echo -e "${GREEN}✓ Successfully removed repository: $repository_name${NC}"
            return 0
        else
            echo -e "${YELLOW}⚠ Skipped: $repository_name${NC}"
            return 1
        fi
    else
        echo -e "${RED}✗ Repository not found: $repository_name${NC}"
        return 1
    fi
}

# Process all repository arguments
success_count=0
skip_count=0
error_count=0

echo -e "${YELLOW}Processing $# repository(ies)...${NC}"
echo ""

for repo_name in "$@"; do
    # Validate repository name
    if ! validate_repo_name "$repo_name"; then
        ((error_count++))
        echo ""
        continue
    fi
    
    # Remove repository
    if remove_repository "$repo_name"; then
        ((success_count++))
    else
        if [ -d "$GIT_SERVER_BASE/$repo_name" ]; then
            ((skip_count++))
        else
            ((error_count++))
        fi
    fi
    echo ""
done

# Summary
echo -e "${GREEN}=== Summary ===${NC}"
echo -e "${GREEN}Successfully removed: $success_count${NC}"
if [ $skip_count -gt 0 ]; then
    echo -e "${YELLOW}Skipped: $skip_count${NC}"
fi
if [ $error_count -gt 0 ]; then
    echo -e "${RED}Errors: $error_count${NC}"
fi
echo -e "${GREEN}Done!${NC}" 